<template>
  <ContentWrap>
    <!-- 两栏布局 -->
    <el-row :gutter="20">

      <!-- 右侧账号列表 (占2/3宽度) -->
      <el-col :span="24">
        <div class="right-panel">
          <!-- 账号列表 -->
          <el-table
            v-loading="accountLoading"
            :data="formattedAccountList"
            :stripe="true"
            :show-overflow-tooltip="true"
            empty-text="暂无账号数据"
          >
            <el-table-column label="ID" align="center" prop="id" width="50"/>
            <el-table-column label="账号" align="center" prop="username"/>
            <el-table-column label="类型" align="center" prop="accountType"/>
            <el-table-column label="操作" align="center" min-width="120px">
              <template #default="scope">
                <el-button
                  link
                  type="primary"
                  @click="openAccountForm('update', scope.row.id)"
                >
                  编辑
                </el-button>
                <el-button
                  link
                  type="primary"
                >
                  分析
                </el-button>
                <el-button
                  link
                  type="danger"
                  @click="handleAccountDelete(scope.row.id)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页 -->
          <Pagination
            :total="accountTotal"
            v-model:page="accountQueryParams.pageNo"
            v-model:limit="accountQueryParams.pageSize"
            @pagination="getAccountList"
            :page-sizes="[5, 10, 20, 50]"
          />
        </div>
      </el-col>
    </el-row>
  </ContentWrap>

  <!-- 账号类型表单弹窗 -->
  <AccountTypeForm ref="typeFormRef" @success="handleTypeFormSuccess"/>
  <!-- 账号表单弹窗 -->
  <InternetAccountForm ref="accountFormRef" @success="getAccountList"/>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, watch } from 'vue'
import { AccountTypeApi, AccountTypeVO } from '@/api/member/accounttype'
import { InternetAccountApi, InternetAccountVO } from '@/api/member/internetaccount'
import AccountTypeForm from '@/views/member/accounttype/AccountTypeForm.vue'
import InternetAccountForm from '@/views/member/internetaccount/InternetAccountForm.vue'

// 国际化与消息提示
const message = useMessage()
const { t } = useI18n()

// 左侧账号类型相关状态
const typeLoading = ref(true)
const typeList = ref<AccountTypeVO[]>([])
const selectedTypeId = ref<number | undefined>(undefined)
const selectedTypeName = ref('')

// 人员详情页传过来的人员ID
const { editPersonId } = defineProps({
  editPersonId: {
    type: [String, Array], // 同时支持字符串和数组类型
    required: true
  }
})

// 右侧账号列表相关状态
const accountLoading = ref(true)
const accountList = ref<InternetAccountVO[]>([])
const accountTotal = ref(0)
const accountQueryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  createTime: [],
  accountTypeId: undefined as number | undefined, // 允许number或undefined
  username: undefined,
  personId: undefined as number | undefined,
})

// 获取账号类型列表（加载全部，不分页）
const getTypeList = async () => {
  typeLoading.value = true;
  try {
    typeList.value = await AccountTypeApi.getAccountTypeList();
  } catch (error) {
    message.error(t('common.fetchFail') + t('accountType.title'))
    console.error('获取账号类型失败:', error)
  } finally {
    typeLoading.value = false;
  }
};

// 获取账号列表
const getAccountList = async () => {
  accountLoading.value = true
  try {
    // 关联左侧选中的类型ID
    accountQueryParams.accountTypeId = selectedTypeId.value
    accountQueryParams.personId = Number(editPersonId)
    const data = await InternetAccountApi.getInternetAccountPage(accountQueryParams)
    accountList.value = data.list
    accountTotal.value = data.total
  } catch (error) {
    message.error(t('common.fetchFail') + t('internetAccount.title'))
    console.error('获取账号列表失败:', error)
  } finally {
    accountLoading.value = false
  }
}

// 左侧类型选中处理
const handleTypeSelect = (row: AccountTypeVO) => {
  selectedTypeId.value = row.id
  selectedTypeName.value = row.name
  accountQueryParams.pageNo = 1 // 重置页码
  getAccountList() // 重新查询账号列表
}

// 清除类型选择
const clearTypeSelect = () => {
  selectedTypeId.value = undefined
  selectedTypeName.value = ''
  accountQueryParams.pageNo = 1
  getAccountList()
}

// 类型行选中样式
const typeRowClassName = ({ row }: { row: AccountTypeVO }) => {
  return row.id === selectedTypeId.value ? 'type-row-selected' : ''
}

// 账号类型表单成功回调
const handleTypeFormSuccess = async () => {
  const currentId = selectedTypeId.value
  await getTypeList()
  // 如果之前有选中项，检查是否还存在
  if (currentId) {
    const stillExists = typeList.value.some(item => item.id === currentId)
    if (!stillExists) {
      clearTypeSelect()
    }
  }
}

// 账号类型操作
const typeFormRef = ref()
const openTypeForm = (type: string, id?: number) => {
  typeFormRef.value.open(type, id)
}

const handleTypeDelete = async (id: number) => {
  try {
    await message.delConfirm()
    await AccountTypeApi.deleteAccountType(id)
    message.success(t('common.delSuccess'))
    // 如果删除的是当前选中的类型，清除选中状态
    if (id === selectedTypeId.value) {
      clearTypeSelect()
    }
    await getTypeList()
  } catch (error) {
    console.error('删除账号类型失败:', error)
  }
}

// 账号列表操作
const accountFormRef = ref()
const openAccountForm = (type: string, id?: number) => {
  accountFormRef.value.open(type, editPersonId, id)
}

const handleAccountDelete = async (id: number) => {
  try {
    await message.delConfirm()
    await InternetAccountApi.deleteInternetAccount(id)
    message.success(t('common.delSuccess'))
    await getAccountList()
  } catch (error) {
    console.error('删除账号失败:', error)
  }
}

// 处理账号列表，添加账号类型名称
const formattedAccountList = computed(() => {
  return accountList.value.map(account => {
    // 根据 accountTypeId 从 typeList 中匹配名称
    const matchedType = typeList.value.find(
      type => type.id === account.accountTypeId
    );
    return {
      ...account,
      accountType: matchedType ? matchedType.name : '未知类型' // 新增 accountType 字段
    };
  });
});

// 监听类型列表变化，同步更新账号显示
watch(typeList, () => {
  // 类型列表变化时重新格式化账号列表
  formattedAccountList.value
})

// 初始化
onMounted(() => {
  getTypeList()
  getAccountList()
})
</script>

<style scoped>
.left-panel, .right-panel {
  background: #fff;
  padding: 16px;
  border-radius: 4px;
  height: 100%;
  min-height: 600px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.panel-title {
  margin-bottom: 16px;
  font-size: 16px;
  font-weight: 500;
  color: #333;
  border-bottom: 1px solid #eee;
  padding-bottom: 8px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 8px;
}

.title-content {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
}

.selected-tag {
  background-color: #e8f4fd;
  color: #165dff;
  border-color: #bfdbfe;
  margin-top: 2px;
  transition: all 0.3s ease;
}

.selected-tag:hover {
  background-color: #dceeff;
}

.title-action-btn {
  margin-top: -4px;
}

/* 选中行样式 */
:deep(.type-row-selected) {
  background-color: #f0f7ff !important;
}

:deep(.type-row-selected:hover > td) {
  background-color: #f0f7ff !important;
}

/* 表格样式优化 */
:deep(.el-table) {
  border-radius: 4px;
  border: 1px solid #ebeef5;
}

:deep(.el-table__empty-text) {
  color: #909399;
}

/* 分页样式 */
:deep(.el-pagination) {
  margin-top: 16px;
  text-align: right;
}

/* 响应式调整 */
@media (max-width: 992px) {
  .el-col {
    width: 100% !important;
  }

  .left-panel {
    margin-bottom: 20px;
  }
}

@media (max-width: 768px) {
  .panel-title {
    flex-direction: column;
    align-items: flex-start;
  }

  .title-action-btn {
    align-self: flex-end;
    margin-top: 8px;
  }
}
</style>
